package cn.iocoder.yudao.module.resource.service.roletextaudio;

import cn.iocoder.yudao.framework.common.pojo.PageResult;
import cn.iocoder.yudao.framework.common.util.object.BeanUtils;
import cn.iocoder.yudao.module.resource.controller.admin.audiotext.vo.AudioTextConvertAudioVO;
import cn.iocoder.yudao.module.resource.controller.admin.audiotext.vo.RoleTextAudioPageReqVO;
import cn.iocoder.yudao.module.resource.controller.admin.audiotext.vo.RoleTextAudioRespVO;
import cn.iocoder.yudao.module.resource.controller.admin.audiotext.vo.RoleTextAudioSaveReqVO;
import cn.iocoder.yudao.module.resource.dal.dataobject.audiotone.AudioToneDO;
import cn.iocoder.yudao.module.resource.dal.dataobject.roletextaudio.RoleTextAudioDO;
import cn.iocoder.yudao.module.resource.dal.mysql.audio.LmAudioMapper;
import cn.iocoder.yudao.module.resource.dal.mysql.audiotone.AudioToneMapper;
import cn.iocoder.yudao.module.resource.dal.mysql.roletextaudio.RoleTextAudioMapper;
import com.alibaba.fastjson.JSON;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import static cn.iocoder.yudao.framework.common.exception.util.ServiceExceptionUtil.exception;
import static cn.iocoder.yudao.module.resource.enums.ErrorCodeConstants.ROLE_TEXT_AUDIO_NOT_EXISTS;

/**
 * 文本生成角色音频数据 Service 实现类
 *
 * @author 芋道源码
 */
@Service
@Validated
@Slf4j
public class RoleTextAudioServiceImpl implements RoleTextAudioService {

    @Resource
    private RoleTextAudioMapper roleTextAudioMapper;
    @Resource
    private LmAudioMapper lmAudioMapper;
    @Resource
    private AudioToneMapper audioToneMapper;

    @Override
    public Integer createRoleTextAudio(RoleTextAudioSaveReqVO createReqVO) {
        // 插入
        RoleTextAudioDO roleTextAudio = BeanUtils.toBean(createReqVO, RoleTextAudioDO.class);
        roleTextAudioMapper.insert(roleTextAudio);
        // 返回
        return roleTextAudio.getId();
    }

    @Override
    public void updateRoleTextAudio(RoleTextAudioSaveReqVO updateReqVO) {
        // 校验存在
        validateRoleTextAudioExists(updateReqVO.getId());
        // 更新
        RoleTextAudioDO updateObj = BeanUtils.toBean(updateReqVO, RoleTextAudioDO.class);
        roleTextAudioMapper.updateById(updateObj);
    }

    @Override
    public void deleteRoleTextAudio(Integer id) {
        // 校验存在
        validateRoleTextAudioExists(id);
        // 删除
        roleTextAudioMapper.deleteById(id);
    }

    private void validateRoleTextAudioExists(Integer id) {
        if (roleTextAudioMapper.selectById(id) == null) {
            throw exception(ROLE_TEXT_AUDIO_NOT_EXISTS);
        }
    }

    @Override
    public RoleTextAudioDO getRoleTextAudio(Integer id) {
        return roleTextAudioMapper.selectById(id);
    }

    @Override
    public PageResult<RoleTextAudioRespVO> getRoleTextAudioPage(RoleTextAudioPageReqVO pageReqVO) {
        PageResult<RoleTextAudioDO> roleTextAudioDOPageResult = roleTextAudioMapper.selectPage(pageReqVO);
        if (!roleTextAudioDOPageResult.getList().isEmpty()) {
            PageResult<RoleTextAudioRespVO> pageResult = BeanUtils.toBean(roleTextAudioDOPageResult, RoleTextAudioRespVO.class);
            List<Integer> roleIds = roleTextAudioDOPageResult.getList().stream().map(c -> c.getAudioToneId()).collect(Collectors.toList());
            List<AudioToneDO> lmCosplayDOS = audioToneMapper.selectBatchIds(roleIds);
            Map<Integer, AudioToneDO> lmCosplayDOMap = lmCosplayDOS.stream().collect(Collectors.toMap(AudioToneDO::getId, c -> c));
            for (RoleTextAudioRespVO roleTextAudioDO : pageResult.getList()) {
                AudioToneDO lmCosplayDO = lmCosplayDOMap.get(roleTextAudioDO.getAudioToneId());
                if (lmCosplayDO != null) {
                    roleTextAudioDO.setAudioToneName(lmCosplayDO.getName());
                }
            }
            return pageResult;
        }
        return new PageResult<>(0L);

    }

    @Override
    public void saveTextRoleAudio(AudioTextConvertAudioVO param) {
        List<RoleTextAudioDO> roleTextAudioDOList = this.roleTextAudioMapper.getRoleTextAudio(param.getAudioToneIds(), param.getTextIds());
        if (!roleTextAudioDOList.isEmpty()) {
            List<Integer> audioIds = roleTextAudioDOList.stream().filter(c -> c.getAudioId() != null).map(c -> c.getAudioId()).collect(Collectors.toList());
            for (RoleTextAudioDO roleTextAudioDO : roleTextAudioDOList) {
                if (roleTextAudioDO.getRelationAudio() != null) {
                    List<Integer> relationAudioList = JSON.parseArray(roleTextAudioDO.getRelationAudio(), Integer.class);
                    audioIds.addAll(relationAudioList);
                }
            }
            if (audioIds.size() > 0) {
                log.info("需要删除的旧音频: {}", audioIds);
                lmAudioMapper.setDeletedAudio(audioIds);
            }
            List<Integer> roleTextIds = roleTextAudioDOList.stream().map(c -> c.getId()).collect(Collectors.toList());
            log.info("删除重复的文本和角色转换记录，{}", roleTextIds);
            roleTextAudioMapper.setDeletedBatch(roleTextIds);
        }
        // 存储新的要转换的数据
        List<RoleTextAudioDO> saveRoleTextAudioDOList = new ArrayList<>(param.getTextIds().size() * param.getAudioToneIds().size());
        for (Integer toneId : param.getAudioToneIds()) {
            for (Integer textId : param.getTextIds()) {
                RoleTextAudioDO roleTextAudioDO = new RoleTextAudioDO();
                roleTextAudioDO.setAudioTextId(textId);
                roleTextAudioDO.setAudioToneId(toneId);
                roleTextAudioDO.setStatus(0);
                saveRoleTextAudioDOList.add(roleTextAudioDO);
            }
        }
        roleTextAudioMapper.insertBatch(saveRoleTextAudioDOList);

    }
}